﻿using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace TruckScale.Helpers
{
  public static class HttpClientHelper
  {
    private static readonly RestClient client = new RestClient("http://zxhq.com.cn:8081");

    // 泛型方法来发送 GET 请求并解析 JSON 响应
    public static async Task<T> GetAsync<T>(string resource) where T : new()
    {
      try
      {
        var request = new RestRequest(resource, Method.Get);
        var response = await client.ExecuteAsync<T>(request);

        if (response.IsSuccessful)
        {
          return response.Data;
        }
        else
        {
          throw new Exception($"请求错误: {response.ErrorMessage}");
        }
      }
      catch (Exception ex)
      {
        throw new Exception($"HTTP 请求异常: {ex.Message}", ex);
      }
    }

    // 发送请求并检查设备是否可用
    public static async Task<bool> IsDeviceAvailable(string machineCode)
    {
      try
      {
        // 构造资源路径
        string resource = $"checkDevice/{machineCode}";

        // 获取并解析响应
        var deviceResponse = await GetAsync<DeviceResponse>(resource);

        // 返回设备的可用状态
        return deviceResponse?.Available ?? false;
      }
      catch (Exception ex)
      {
        // 处理异常，可以记录日志或抛出
        throw new Exception($"检查设备可用状态时出错: {ex.Message}", ex);
      }
    }

    // 发送请求并获取版本信息
    public static async Task<VersionResponse> GetVersionInfo()
    {
      try
      {
        // 构造资源路径
        string resource = "checkVersion";

        // 获取并解析响应
        return await GetAsync<VersionResponse>(resource);
      }
      catch (Exception ex)
      {
        // 处理异常，可以记录日志或抛出
        throw new Exception($"获取版本信息时出错: {ex.Message}", ex);
      }
    }

    // 下载文件并保存到指定路径
    public static async Task DownloadFileAsync(int id, string localFilePath)
    {
      try
      {
        // 构造资源路径
        string resource = $"getVersion/{id}";

        // 创建请求
        var request = new RestRequest(resource, Method.Get);

        // 获取响应流
        var response = await client.ExecuteAsync(request);

        if (response.IsSuccessful)
        {
          // 确保目录存在
          var directory = Path.GetDirectoryName(localFilePath);
          if (!Directory.Exists(directory))
          {
            Directory.CreateDirectory(directory);
          }

          // 使用 FileStream 进行异步写入文件
          using (var fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
          {
            await fileStream.WriteAsync(response.RawBytes, 0, response.RawBytes.Length);
          }

          // 返回成功消息
          Console.WriteLine($"文件下载成功，保存到: {localFilePath}");
        }
        else
        {
          throw new Exception($"文件下载错误: {response.ErrorMessage}");
        }
      }
      catch (Exception ex)
      {
        // 处理异常，可以记录日志或抛出
        throw new Exception($"文件下载时出错: {ex.Message}", ex);
      }
    }

    // 发送 POST 请求并上传文件及其他数据
    public static async Task UploadWeighData(string bh, string weighJson)
    {
      try
      {
        await Task.Delay(5000); // 延迟5秒等待照片抓拍完成

        var client = new RestClient("http://localhost:8080");
        var request = new RestRequest("/uploadRecord", Method.Post);

        // 添加机器码和重量作为参数
        request.AddParameter("machinecode", Global._weighConfig["UploadMachineCode"]);
        request.AddParameter("weighbh", bh);

        // 添加 JSON 数据
        request.AddParameter("json", weighJson);

        // 添加图片文件
        List<string> imagePaths = Directory.GetFiles($"./Snap/{bh}/")
                                           .Select(Path.GetFullPath)
                                           .ToList();
        foreach (var imagePath in imagePaths)
        {
          byte[] imageData = File.ReadAllBytes(imagePath);
          string fileName = Path.GetFileName(imagePath);
          request.AddFile("images", imageData, fileName, "image/jpeg");
        }

        // 设置为多部分表单数据
        request.AlwaysMultipartFormData = true;

        var response = await client.ExecuteAsync(request);

        if (response.IsSuccessful)
        {
          Console.WriteLine("Data and images uploaded successfully!");
        }
        else
        {
          throw new Exception("Error uploading data and images: " + response.ErrorMessage);
        }
      }
      catch (Exception ex)
      {
        throw new Exception("Exception: " + ex.Message, ex);
      }
    }

  }

  // 映射 JSON 响应的类
  public class DeviceResponse
  {
    public int Id { get; set; }
    public string Machinecode { get; set; }
    public string Regcode { get; set; }
    public DateTime Createtime { get; set; }
    public DateTime Requesttime { get; set; }
    public bool Available { get; set; }
  }

  // 映射 checkVersion 响应的类
  public class VersionResponse
  {
    public int Id { get; set; }
    public string Version { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }
  }
}
